#include "accountdialog.h"
#include "ui_accountdialog.h"

AccountDialog::AccountDialog(QWidget *parent, IcySettings *fSettings,
                             IcyBuddies *fBuddies) :
    QDialog(parent),
    ui(new Ui::AccountDialog)
{
    ui->setupUi(this);
    settings = fSettings;
    buddies = fBuddies;
    setupWindow();
}

AccountDialog::~AccountDialog()
{
    delete ui;
}

void AccountDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void AccountDialog::setupWindow()
{
    setWindowIcon(settings->getIcon("status://offline"));
    setWindowTitle(tr("IcyQt - Select your account"));

    ui->passLE->setText(tr("Password:"));
    ui->savePassCB->setText(tr("Save password"));
    setWindowFlags(Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
    connect(ui->accountsCB, SIGNAL(currentIndexChanged(int)),
            this, SLOT(onIndexChanged(int)));

//    accounts = 0;

    settings->getAccounts(&accounts);

    if ( accounts.count() == 0 )
        return;

    for ( int i = 0; i < accounts.count(); i++ ){
//        qDebug() << i << '\t' << accounts.at(i).sScreenName;
        ui->accountsCB->addItem(settings->getIcon("icq"), accounts.at(i).sScreenName);
    }
    if ( accounts.count() > 0 )
        ui->accountsCB->setCurrentIndex(accounts.count());
//    qDebug() << "Done";
}

int AccountDialog::findInAccs(const QString &sScreenName)
{
    for ( int i = 0; i < accounts.count(); i++ ){
        if ( accounts[i].sScreenName == sScreenName )
            return i;
    }
    return -1;
}

/***********************************************************************
                SLOTS
***********************************************************************/

void AccountDialog::on_buttonBox_accepted()
{
//    setVisible(false);
    int iIndex = findInAccs(ui->accountsCB->currentText());
    settings->saveAccount(ui->accountsCB->currentText(),
                          ui->passLE->text(),
                          ui->savePassCB->isChecked(),
                          iIndex);
    mainWindow = new MainWindow(0, settings, buddies);
    mainWindow->show();
    mainWindow->setAccount(accounts.takeAt(iIndex));
    close();
}

void AccountDialog::on_buttonBox_rejected()
{
    close();
}

void AccountDialog::onIndexChanged(const int iIndex)
{
    ui->passLE->setText(accounts.at(iIndex-1).sPassword);
    ui->savePassCB->setChecked(accounts.at(iIndex-1).bSavePassword);
}
